import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Card, message, Row, Col, Select, Button, Input, Tabs, Modal, InputNumber, DatePicker, Divider } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import { urlParse } from '@/utils/utils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import StandardTable from '@/components/StandardTable';
import LocalPolicy from './LocalPolicy/Index'; // 引用组件
import DictCode from '../../components/DictCode';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Option } = Select;
const { RangePicker } = DatePicker;

@connect(({ localpolicy }) => ({
  localpolicy,
  dictionaryData: localpolicy.dictionaryData,
  contributorData: localpolicy.contributorData,
  totaldataSource: localpolicy.totaldataSource,
  insuranceIds: localpolicy.insuranceIds,
  addTime: localpolicy.addTime,
  current: localpolicy.current,
  pageData: localpolicy.pageData, // 减免政策列表数据
  echoPolicyObj: localpolicy.echoPolicyObj, // 减免政策的回显
}))
@Form.create()
class BasicList extends PureComponent {
  state = {
    hshdRegFlag: '',
    vno: '',
    selectedRows: [],
    selectedRowKeys: [],
    visible: false, // 添加、修改减免政策的弹框显隐
    remisId: null, // 减免id
    insLsPkgId: null, // 组合id
  };

  componentWillUnmount() {
    const { dispatch } = this.props;
    const resetInfo = {
      personnelcategory: {}, // 组合名称和区分缴费人员类别标识
      personnelcategoryData: [], // 获取缴费人员类别信息
      personnelinsuranceData: [], // 人员险种列表
      insuranceInformationData: [], // 当前险种所有信息
      dictionaryData: {}, // 字典值
      bizActiveKey: '',
      type: '',
      contributorData: [], // 缴费人员类别信息列表
      totaldataSource: [], // 总数据源
      payerIds: '', // 缴费人员类别id
      insuranceIds: '', // 险种id
      rangeDate: '', // 禁用开始和时间
      beginDate: '',
      ideIdsMessage: '', //
      addTime: [],
      groupId: '', // 组id
      current: 0,
      viewDataMessage: {}, // 查看右侧数据
      changeDataMessage: {}, // 查看右侧数据
      isModify: '', // 是不是修改的弹窗
      insLsPkgmessage: {}, // 组合信息
      providentFundPolicyId: '', // 政策组id
      personnelData: {},
      insureArr: [], // 五个险种
      clearProvidentFundId: '',
      provinceId: '', // 省 id
    };
    dispatch({
      type: 'localpolicy/updateModelData',
      payload: { ...resetInfo },
    });
  }

  // 点击保存
  prev = () => {
    const { dispatch, localpolicy, form } = this.props;
    const { vno } = this.state;
    const insLsPkgName = form.getFieldValue('insLsPkgName');
    dispatch({
      type: 'localpolicy/changeGroupName',
      payload: {
        insLsPkgId: localpolicy.groupId,
        vno,
        insLsPkgName,
      },
      callback: res => {
        if (res.success) {
          message.success('修改成功！');
          router.goBack();
        } else {
          message.warning('修改失败！');
          router.goBack();
        }
      },
    });
  };

  componentDidMount = () => {
    const { dispatch, location, pageData: { pagination } } = this.props;
    const url = location.search;
    const { insLsPkgId } = urlParse(decodeURIComponent(url));
    const { areaId, hshdRegFlag, vno } = urlParse(url);
    this.setState({
      hshdRegFlag,
      vno,
      insLsPkgId,
    });
    dispatch({
      type: 'localpolicy/cityId',
      payload: areaId,
    });
    dispatch({
      type: 'localpolicy/getDictCode',
      payload: ['YES_NO_FLAG', 'BIZ_INS_TYPE', 'CARRY_RULE'],
    });
    // 查看缴费组的id和是否区分缴费人员类别
    dispatch({
      type: 'localpolicy/paymentGroupId',
      payload: { insLsPkgId },
      callback: response => {
        if (Number(response.hshdRegFlag) === 1) {
          dispatch({
            type: 'localpolicy/contributorCategory',
            payload: { areaId },
            callback: res => {
              const paramet = {
                insLsPkgId: response.insLsPkgId,
                joinIdeId: res[0].ideId,
                type: '3',
              };
              // 获取该缴费人员下该险种下的所有信息
              dispatch({
                type: 'localpolicy/insuranceInformation',
                payload: paramet,
              });
            },
          });
        } else {
          const paramet = {
            insLsPkgId: response.insLsPkgId,
            type: '3',
          };
          // 获取该缴费人员下该险种下的所有信息
          dispatch({
            type: 'localpolicy/insuranceInformation',
            payload: paramet,
          });
        }
      },
    });
    this.getReliefPolicyList(pagination.current, pagination.pageSize, insLsPkgId);
  };

  // 切换缴费人员类别
  ideTabChange = value => {
    if (value) {
      const { dispatch, localpolicy } = this.props;
      dispatch({
        type: 'localpolicy/changeMessage',
        payload: { value },
      });
      const paramet = {
        insLsPkgId: localpolicy.groupId,
        joinIdeId: value,
        type: '3',
      };
      // 添加完以后获取该缴费人员下该险种下的所有信息
      dispatch({
        type: 'localpolicy/insuranceInformation',
        payload: paramet,
      });

      // 清空默认值
      dispatch({
        type: 'localpolicy/clearDefault',
        payload: {},
      });
    }
  };

  registChange = e => {
    this.setState({
      hshdRegFlag: e,
    });
  };

  // 获取减免政策列表数据
  getReliefPolicyList = (currentPage = 1, pageSize = 10, insLsPkgId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/fetchReliefPolicy',
      payload: {
        pageArg: { currentPage, pageSize },
        insLsPkgId,
      },
    });
  }

  // 点击添加、修改减免政策
  openReliefPolicy = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/updateModelData',
      payload: {
        echoPolicyObj: {},
      },
    });
    this.setState({ remisId: null });
    if (record) { // 修改
      // 回显接口
      dispatch({
        type: 'localpolicy/getLocRemission',
        payload: {
          remisId: record.remisId,
        },
      });
      this.setState({ remisId: record.remisId, vno: record.vno });
    }
    this.setState({ visible: true });
  }

  // 点击确定按钮
  handleOk = () => {
    const { form, dispatch, localpolicy, pageData: { pagination } } = this.props;
    const { remisId, vno } = this.state;
    form.validateFields([
      'type',
      'entpType',
      'remissionPeriod',
      'corpProp',
    ],(err, values) => {
      if (!err) {
        Object.keys(values).forEach(key => {
          const temp = values;
          if (key === 'remissionPeriod') { // 减免时间段
            temp.remisEndYm = values.remissionPeriod && moment(values.remissionPeriod[1]).valueOf() || undefined;
            temp.remisBeginYm = values.remissionPeriod && moment(values.remissionPeriod[0]).valueOf() || undefined;
            delete temp.remissionPeriod;
          } else if (key === 'type' || key === 'corpProp') { // 险种或者企业应缴比例
            temp.type = Number(temp.type);
            temp.corpProp = Number(temp.corpProp);
          } else if (key === 'entpType') { // 企业类型
            temp.entpType = temp.entpType.toString();
          }
        })
        const params = {
          ...values,
          insLsPkgId: localpolicy.groupId,
        }
        if (remisId) {  // 修改后的提交
          dispatch({
            type: 'localpolicy/fetchUpdatePolicy',
            payload: {
              remisId,
              ...params,
              vno: Number(vno),
            },
          }).then(res => {
            if (res.success) {
              message.success('修改成功');
              this.setState({ visible: false });
              this.getReliefPolicyList(pagination.current, pagination.pageSize, localpolicy.groupId);
            }
          })
        } else {
          dispatch({
            type: 'localpolicy/fetchSavePolicy',
            payload: params,
          }).then(res => {
            if (res.success) {
              message.success('添加成功');
              this.setState({ visible: false });
              this.getReliefPolicyList(pagination.current, pagination.pageSize, localpolicy.groupId);
            }
          })
        }
      }
    })
  }

  // 删除减免政策
  delReliefPolicy = (record) => {
    const { dispatch, pageData: { pagination }, localpolicy } = this.props;
    Modal.confirm({
      icon: <QuestionCircleOutlined />,
      title: '删除',
      content: '确认删除吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'localpolicy/fetchDeletePolicy',
          payload: {
            remisId: record.remisId,
            vno: record.vno,
          },
        }).then(res => {
          if (res.success) {
            message.success('删除成功');
            this.getReliefPolicyList(pagination.current, pagination.pageSize, localpolicy.groupId);
          }
        });
      },
    });
  }

  // 点击弹框取消按钮
  handleCancel = () => {
    this.setState({  visible: false });
  }

  // 点击复选框
  handleSelectRows = (rows, rowKeys) => {
    this.setState({ selectedRows: rows, selectedRowKeys: rowKeys });
  };

  // 点击分页
  handleStandardTableChange = pagination => {
    const { insLsPkgId } = this.state;
    this.getReliefPolicyList(pagination.current, pagination.pageSize, insLsPkgId);
  };


  render() {
    const { form, contributorData, localpolicy, pageData, echoPolicyObj } = this.props;
    const { hshdRegFlag, selectedRows, selectedRowKeys, visible, remisId } = this.state;
    const formItemLayout = {
      labelCol: { md: { span: 14 } },
      wrapperCol: { md: { span: 8 } },
    };
    const formItemLayout2 = {
      labelCol: { md: { span: 10 } },
      wrapperCol: { md: { span: 12 } },
    };
    const modalsLayout = {
      labelCol: {
        xs: {
          span: 7,
        },
      },
      wrapperCol: {
        xs: {
          span: 17,
        },
      },
    };
    const { getFieldDecorator } = form;
    // 减免政策表格
    const reliefPolicyColumns = [
      {
        title: '险种',
        dataIndex: 'typeName',
        render: val => (val && val) || '--',
      },
      {
        title: '企业类型',
        dataIndex: 'entpTypeName',
        render: val => (val && val) || '--',
      },
      {
        title: '减免时间段',
        dataIndex: 'remissionPeriod',
        render: (text, record) => (
          <span>
            {record.remisBeginYm && moment(record.remisBeginYm).format('YYYY-MM') || '--'}
            -
            {record.remisEndYm && moment(record.remisEndYm).format('YYYY-MM') || '--'}
          </span>
        )
      },
      {
        title: '企业应缴比例',
        dataIndex: 'corpProp',
        render: val => val === 0 ? '0%' : (val && `${val}%`) || '--',
      },
      {
        title: '添加时间',
        dataIndex: 'creTime',
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'opertion',
        render: (text, record) => (
          <Fragment>
            <span>
              <a
                onClick={() => this.openReliefPolicy(record)}
              >
                修改
              </a>
              <Divider type="vertical" />
              <a onClick={() => this.delReliefPolicy(record)}>删除</a>
            </span>
          </Fragment>
        ),
      },
    ];
    return (
      <div>
        <PageHeaderWrapper />
        <Card style={{ marginTop: 12, marginLeft: 12, marginRight: 12 }}>
          <div style={{ marginTop: 22 }}>
            <Form onSubmit={this.handleSubmit}>
              <Row style={{ marginBottom: 50, padding: '0 40px', width: '100%' }}>
                <Col span={8}>
                  <FormItem {...formItemLayout2} label="组合名称">
                    {getFieldDecorator('insLsPkgName', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: localpolicy.insLsPkgmessage.insLsPkgName,
                    })(<Input placeholder="请输入" maxLength={30} />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label="是否区分缴费人员类别">
                    {getFieldDecorator('hshdRegFlagName', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: localpolicy.insLsPkgmessage.hshdRegFlagName,
                    })(
                      <Select
                        onChange={this.registChange}
                        style={{ width: '100%' }}
                        placeholder="请选择"
                        disabled
                      >
                        <Option key="1">是</Option>
                        <Option key="2">否</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Form>
            <div>
              <div>
                {Number(hshdRegFlag) === 1 ? (
                  <Tabs
                    defaultActiveKey={contributorData[0] ? contributorData[0].ideId : ''}
                    onChange={this.ideTabChange}
                    type="card"
                  >
                    {contributorData.map(value => (
                      <TabPane tab={value.ideName} key={value.ideId}>
                        <LocalPolicy
                          {...this.props}
                          isprovidentFund={1}
                          viewDataMessage={localpolicy.viewDataMessage}
                          isaddBtn={1}
                          hshdRegFlag={1}
                          insuranceInformationData={localpolicy.insuranceInformationData}
                        />
                      </TabPane>
                    ))}
                  </Tabs>
                ) : (
                  <LocalPolicy
                    {...this.props}
                    isprovidentFund={1}
                    viewDataMessage={localpolicy.viewDataMessage}
                    isaddBtn={1}
                    hshdRegFlag={2}
                    insuranceInformationData={localpolicy.insuranceInformationData}
                  />
                )}
              </div>
            </div>
            {/* 减免政策 */}
            <div style={{ marginTop: 20 }}>
              <h3
                style={{
                  fontSize: 14,
                  height: '54px',
                  lineHeight: '54px',
                  backgroundColor: 'rgba(250, 250, 250)',
                  padding: '0 16px',
                }}
              >
                减免政策
              </h3>
              <Row style={{ padding: '16px 0 16px 16px' }}>
                <Button type="primary" style={{ marginRight: 20 }} onClick={() => this.openReliefPolicy()}>
                  <PlusOutlined />
                  添加
                </Button>
              </Row>
              <StandardTable
                style={{ margin: '5px 0 20px 0' }}
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                data={pageData}
                columns={reliefPolicyColumns}
                rowKey={record => record.remisId}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
              {
                visible && (
                  <Modal
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    title={remisId ? '修改减免政策' : '添加减免政策'}
                    okText="确定"
                    destroyOnClose
                  >
                    <Form>
                      <Row span={24}>
                        <Col span={22}>
                          <FormItem {...modalsLayout} label="险种">
                            {getFieldDecorator('type', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择',
                                },
                              ],
                              initialValue: echoPolicyObj && echoPolicyObj.type && echoPolicyObj.type.toString(),
                            })(
                              <DictCode
                                allowClear
                                showSearch
                                filterOption={(input, option) =>
                                  option.props.children
                                    .toLowerCase()
                                    .indexOf(input.toLowerCase()) >= 0
                                }
                                dictType="BIZ_INS_TYPE"
                                style={{ width: '100%' }}
                                disabled={remisId}
                              />
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row span={24}>
                        <Col span={22}>
                          <FormItem {...modalsLayout} label="企业类型">
                            {getFieldDecorator('entpType', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择',
                                },
                              ],
                              initialValue: echoPolicyObj && echoPolicyObj.entpType && echoPolicyObj.entpType.split(","),
                            })(
                              <DictCode
                                allowClear
                                showSearch
                                filterOption={(input, option) =>
                                  option.props.children
                                    .toLowerCase()
                                    .indexOf(input.toLowerCase()) >= 0
                                }
                                dictType="ENTP_TYPE"
                                style={{ width: '100%' }}
                                mode="multiple"
                                disabled={remisId}
                              />
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row span={24}>
                        <Col span={22}>
                          <FormItem {...modalsLayout} label="减免时间段">
                            {getFieldDecorator('remissionPeriod', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择',
                                },
                              ],
                              initialValue: echoPolicyObj.remisBeginYm && echoPolicyObj.remisEndYm &&
                              [moment(echoPolicyObj.remisBeginYm),moment(echoPolicyObj.remisEndYm)] || undefined,
                            })(
                              <RangePicker
                                placeholder={['开始年月', '结束年月']}
                                picker="month"
                                style={{ width: '100%' }}
                                allowClear
                                format="YYYY-MM"
                                disabled={remisId}
                              />
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                      <Row span={24}>
                        <Col span={22}>
                          <FormItem {...modalsLayout} label="企业应缴比例">
                            {getFieldDecorator('corpProp', {
                              rules: [
                                {
                                  required: true,
                                  message: '小数点后不可超过4位',
                                  pattern: /^-?\d+\.?\d{0,4}$/,
                                },
                              ],
                              initialValue: echoPolicyObj && echoPolicyObj.corpProp,
                            })(
                              <InputNumber
                                style={{ width: '100%' }}
                                placeholder="请输入"
                                formatter={value => `${value}%`}
                                parser={value => value.replace('%', '')}
                              />
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                    </Form>
                  </Modal>
                )
              }
            </div>
            <p style={{ textAlign: 'center' }}>
              <Button type="primary" style={{ marginLeft: 30 }} size="large" onClick={() => this.prev()}>
                保存
              </Button>
            </p>
          </div>
        </Card>
      </div>
    );
  }
}
const BasicListFrom = Form.create()(BasicList);
export default BasicListFrom;
